package com.maiji.cloud.scheduled;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.maiji.cloud.entities.community.ComMsgInfo;
import com.maiji.cloud.entities.login.UploadRecord;
import com.maiji.cloud.microservice.UploadRecordService;
import com.maiji.cloud.service.ComCommentService;
import com.maiji.cloud.service.CommunityService;
import com.maiji.cloud.utils.BaiduAI;
import org.apache.commons.lang.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class ScheduledService {

    private static final Logger logger = LoggerFactory.getLogger(ScheduledService.class);
    @Autowired
    private CommunityService communityService;
    @Autowired
    private UploadRecordService uploadRecordService;
    @Autowired
    private ComCommentService comCommentService;

    // 定时审核动态标题、内容和图片
    @Scheduled(cron = "${cron.examineMsg}")
    public void examineMsg () {
        EntityWrapper<ComMsgInfo> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("examined", 0);
        entityWrapper.eq("isolation", false);
        entityWrapper.orderBy("publish_time", false);
        List<ComMsgInfo> comMsgInfos = communityService.selectList(entityWrapper);
        comMsgInfos = comMsgInfos.parallelStream().limit(50L).collect(Collectors.toList());
        List<String> msgIds = comMsgInfos.parallelStream().map(ComMsgInfo::getMsgId).collect(Collectors.toList());
        Map<String, List<UploadRecord>> imgListMap = uploadRecordService.findAllByBelongIds(msgIds)
                .parallelStream().collect(Collectors.groupingBy(UploadRecord::getBelongId));
        List<ComMsgInfo> trueMsgs = Lists.newArrayList();
        List<ComMsgInfo> falseMsgs = Lists.newArrayList();
        for (ComMsgInfo msg: comMsgInfos) {
            /*try {
                Thread.sleep(222);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            StringBuilder text = new StringBuilder();
            if (StringUtil.isNotBlank(msg.getTitle())) text.append(msg.getTitle());
            if (StringUtil.isNotBlank(msg.getContent())) text.append(msg.getContent());
            if (StringUtil.isNotBlank(text.toString())) {
                Boolean examineText = BaiduAI.examineText(text.toString());
                if (examineText == null) continue; // 审核标题和内容有报错，跳过，下次在审核
                if (BooleanUtils.isFalse(examineText)) {
                    falseMsgs.add(msg.setIsolation(true).setExamined(true));
                    continue;
                }
            }*/
            List<UploadRecord> uploadRecords = imgListMap.get(msg.getMsgId());
            if (uploadRecords != null) {
                for (UploadRecord img: uploadRecords) {
                    try {
                        Thread.sleep(555);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Boolean examineImg = BaiduAI.examineImg(img.getUrl());
                    if (examineImg == null) break; // 审核图片有报错，跳过，下次在审核
                    if (BooleanUtils.isFalse(examineImg)) {
                        falseMsgs.add(msg.setIsolation(true).setExamined(1));
                        break;
                    }
                }
                if (! msg.getIsolation()) trueMsgs.add(msg.setExamined(1));
            } else trueMsgs.add(msg.setExamined(1));
        }
        if (trueMsgs.size() > 0) communityService.updateBatchById(trueMsgs);
        if (falseMsgs.size() > 0) communityService.updateBatchById(falseMsgs);
        logger.info("定时审核动态 ===>> 通过 ===>> msgIds = {}", trueMsgs.parallelStream().map(ComMsgInfo::getMsgId).collect(Collectors.toList()));
        logger.info("定时审核动态 ===>> 屏蔽 ===>> msgIds = {}", falseMsgs.parallelStream().map(ComMsgInfo::getMsgId).collect(Collectors.toList()));
    }

    // 定时审核动态评论内容
    /*@Scheduled(cron = "${cron.examineMsg}")
    public void examineMsgComment () {
        EntityWrapper<ComComment> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("examined", 0);
        entityWrapper.orderBy("publish_time", false);
        List<ComComment> comComments = comCommentService.selectList(entityWrapper);
        comComments = comComments.stream().map(msgc -> {
            try {
                Thread.sleep(222);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (StringUtil.isNotBlank(msgc.getContent()))
                if (! BaiduAI.examineText(msgc.getContent()))
                    return msgc.setDelete(3).setDeleteReason("自动审核未通过");
            return msgc.setReadAlready(1);
        }).collect(Collectors.toList());
        String updateBatchById = comCommentService.updateBatchById(comComments) ? "成功" : "失败";
        logger.info("定时审核动态评论 ===>> {} ===>> msgCommentIds = {}", updateBatchById, comComments
                .parallelStream().map(ComComment::getCommentId).collect(Collectors.toList()));
    }*/

}
